#!/bin/bash
###############################################################################
# FreeRTOS Download and Setup Script
# This script downloads FreeRTOS v10.4.6 and sets up the required files
###############################################################################

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
FREERTOS_DIR="$PROJECT_ROOT/Middlewares/FreeRTOS"
FREERTOS_VERSION="V10.4.6"
FREERTOS_URL="https://github.com/FreeRTOS/FreeRTOS-Kernel/archive/refs/tags/${FREERTOS_VERSION}.tar.gz"
TEMP_DIR="/tmp/freertos_download"

echo "=========================================="
echo "FreeRTOS Download and Setup Script"
echo "=========================================="
echo "Version: ${FREERTOS_VERSION}"
echo "Target: ${FREERTOS_DIR}"
echo ""

# Create directories
echo "[1/5] Creating directories..."
mkdir -p "$FREERTOS_DIR"
mkdir -p "$TEMP_DIR"

# Download FreeRTOS
echo "[2/5] Downloading FreeRTOS ${FREERTOS_VERSION}..."
if [ -f "$TEMP_DIR/freertos.tar.gz" ]; then
    echo "  - Using cached download"
else
    if command -v curl &> /dev/null; then
        curl -L "$FREERTOS_URL" -o "$TEMP_DIR/freertos.tar.gz"
    elif command -v wget &> /dev/null; then
        wget "$FREERTOS_URL" -O "$TEMP_DIR/freertos.tar.gz"
    else
        echo "Error: Neither curl nor wget found. Please install one of them."
        exit 1
    fi
    echo "  - Download complete"
fi

# Extract FreeRTOS
echo "[3/5] Extracting FreeRTOS..."
cd "$TEMP_DIR"
tar -xzf freertos.tar.gz
EXTRACTED_DIR=$(find . -maxdepth 1 -type d -name "FreeRTOS-Kernel-*" | head -n 1)

if [ -z "$EXTRACTED_DIR" ]; then
    echo "Error: Failed to find extracted directory"
    exit 1
fi

# Copy required files
echo "[4/5] Copying FreeRTOS files..."

# Copy source files
echo "  - Copying source files..."
mkdir -p "$FREERTOS_DIR/Source"
cp "$EXTRACTED_DIR/tasks.c" "$FREERTOS_DIR/Source/"
cp "$EXTRACTED_DIR/queue.c" "$FREERTOS_DIR/Source/"
cp "$EXTRACTED_DIR/list.c" "$FREERTOS_DIR/Source/"
cp "$EXTRACTED_DIR/timers.c" "$FREERTOS_DIR/Source/"
cp "$EXTRACTED_DIR/event_groups.c" "$FREERTOS_DIR/Source/"
cp "$EXTRACTED_DIR/stream_buffer.c" "$FREERTOS_DIR/Source/"

# Copy include files
echo "  - Copying include files..."
mkdir -p "$FREERTOS_DIR/Source/include"
cp "$EXTRACTED_DIR/include"/*.h "$FREERTOS_DIR/Source/include/"

# Copy portable files for ARM Cortex-M7
echo "  - Copying portable files (ARM Cortex-M7)..."
mkdir -p "$FREERTOS_DIR/Source/portable/GCC/ARM_CM7/r0p1"
cp "$EXTRACTED_DIR/portable/GCC/ARM_CM7/r0p1/port.c" "$FREERTOS_DIR/Source/portable/GCC/ARM_CM7/r0p1/"
cp "$EXTRACTED_DIR/portable/GCC/ARM_CM7/r0p1/portmacro.h" "$FREERTOS_DIR/Source/portable/GCC/ARM_CM7/r0p1/"

# Copy memory management (heap_4)
echo "  - Copying memory management (heap_4)..."
mkdir -p "$FREERTOS_DIR/Source/portable/MemMang"
cp "$EXTRACTED_DIR/portable/MemMang/heap_4.c" "$FREERTOS_DIR/Source/portable/MemMang/"

# Create directory structure info
echo "[5/5] Creating directory structure..."
cat > "$FREERTOS_DIR/README.md" << 'EOF'
# FreeRTOS v10.4.6

This directory contains FreeRTOS kernel files for the H743-V2 Flight Control System.

## Directory Structure

```
FreeRTOS/
├── Source/
│   ├── tasks.c              # Task management
│   ├── queue.c              # Queue management
│   ├── list.c               # List management
│   ├── timers.c             # Software timers
│   ├── event_groups.c       # Event groups
│   ├── stream_buffer.c      # Stream buffers
│   ├── include/             # FreeRTOS headers
│   ├── portable/
│   │   ├── GCC/
│   │   │   └── ARM_CM7/
│   │   │       └── r0p1/
│   │   │           ├── port.c        # Port for ARM Cortex-M7
│   │   │           └── portmacro.h   # Port macros
│   │   └── MemMang/
│   │       └── heap_4.c     # Memory management (heap_4)
│   └── ...
└── README.md
```

## Configuration

FreeRTOS is configured via `Config/FreeRTOSConfig.h` in the project root.

## Version

- **FreeRTOS Kernel**: v10.4.6
- **Port**: GCC/ARM_CM7/r0p1
- **Memory Management**: heap_4

## License

FreeRTOS is distributed under the MIT License.
See: https://www.freertos.org/a00114.html

## Documentation

- Official Documentation: https://www.freertos.org/
- API Reference: https://www.freertos.org/a00106.html
- Developer Docs: https://www.freertos.org/FreeRTOS-quick-start-guide.html
EOF

# Cleanup
echo ""
echo "Cleaning up temporary files..."
# rm -rf "$TEMP_DIR"

echo ""
echo "=========================================="
echo "FreeRTOS Setup Complete!"
echo "=========================================="
echo ""
echo "Files installed to: $FREERTOS_DIR"
echo ""
echo "Next steps:"
echo "  1. Review Config/FreeRTOSConfig.h"
echo "  2. Build the project: make clean && make all"
echo "  3. Flash to board: make flash"
echo ""
echo "FreeRTOS files:"
ls -lh "$FREERTOS_DIR/Source/" 2>/dev/null || echo "  (Run this script to download)"
echo ""

